package com.example.demo.controller;

import com.example.demo.entity.User;
import com.example.demo.util.ResData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author 成斌
 * @date 2022/10/23
 */
@RestController
public class AdminController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @GetMapping("/get/demo")
    public String get(){
        System.out.println("程序执行成功！！！");
        return "成斌 ---> coming ---> 666666666666666";
    }

    /**
     * 查询操作
     * @return
     */
    @GetMapping("/get/user/{id}")
    public ResData<User> getUser(@PathVariable String id){
        String sql = "select * from user where id = ?";
        User user = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<>(User.class), id);
        return ResData.success(user);
    }

    /**
     * 查询记录数
     * @return
     */
    @GetMapping("/get/count")
    public ResData<Object> getUser(){
        String sql = "select count(*) from user";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return ResData.success(count);

    }

    /**
     * 查询所有
     * @return
     */
    @GetMapping("/get/users")
    public ResData<List<User>> getUsers(){
        String sql = "select * from user";
        List<User> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
        return ResData.success(users);

    }

    /**
     * 添加操作
     * @param user
     * @return
     */
    @PostMapping("/save/user")
    public ResData<Object> getUsers(@RequestBody User user){
        String sql = "insert into user(id,name,age) values (?,?,?)";
        int result = jdbcTemplate.update(sql, user.getId(), user.getName(), user.getAge());
        return result > 0 ? ResData.createSuccess(null) : ResData.failed();
    }

    /**
     * 修改操作
     * @param user
     * @return
     */
    @PutMapping("/update/user")
    public ResData<Object> updateUser(@RequestBody User user){
        String sql = "update user set name = ?,age = ? where id = ?";
        int result = jdbcTemplate.update(sql, user.getName(), user.getAge(), user.getId());
        return result > 0 ? ResData.createSuccess(null) : ResData.failed();
    }

    /**
     * 删除操作
     * @param id
     * @return
     */
    @DeleteMapping("/delete/user/{id}")
    public ResData<List<User>> deleteUser(@PathVariable String id){
        String sql = "delete from user where id = ?";
        int result = jdbcTemplate.update(sql, id);
        return  result > 0 ? ResData.deleteSuccess(null) : ResData.failed();
    }


}
